import { Injectable, Logger, BadRequestException } from "@nestjs/common";
import { DataSource } from "typeorm";
import { CharacterResourcesEntity } from "../entities/character-resources.entity";

@Injectable()
export class BankService {
  private readonly logger = new Logger(BankService.name);

  constructor(private readonly dataSource: DataSource) { }

  /**
   * 金币存入银行
   * @param characterId 角色ID
   * @param amount 存入金额
   * @returns 操作结果
   */
  async depositGold(characterId: number, amount: number): Promise<any> {
    if (amount <= 0) {
      throw new BadRequestException("存入金额必须大于0");
    }

    const queryRunner = this.dataSource.createQueryRunner();

    try {
      // 开始事务
      await queryRunner.connect();
      await queryRunner.startTransaction();

      // 获取角色资源信息
      const resources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );

      if (!resources) {
        throw new BadRequestException("角色资源信息不存在");
      }

      // 检查普通金币余额是否足够
      if (resources.gold < amount) {
        throw new BadRequestException("普通金币余额不足");
      }

      // 确保amount是数字类型
      const numAmount = Number(amount);

      // 验证转换后的数字是否有效
      if (isNaN(numAmount)) {
        throw new BadRequestException("无效的金额格式");
      }

      // 扣除普通金币
      await queryRunner.manager.update(
        CharacterResourcesEntity,
        { characterId },
        {
          gold: () => `gold - ${numAmount}`,
          balanceGold: () => `balanceGold + ${numAmount}`,
          updated_at: new Date(),
        }
      );

      // 提交事务
      await queryRunner.commitTransaction();

      this.logger.log(`✅ 角色 ${characterId} 成功存入金币 ${numAmount}`);

      return {
        success: true,
        message: "金币存入成功",
        data: {
          balanceGold: (+resources.balanceGold || 0) + numAmount,
          balanceMoney: resources.balanceMoney || 0,
          gold: +resources.gold - numAmount,
          money: resources.silver || 0,
        },
      };
    } catch (error: any) {
      // 回滚事务
      await queryRunner.rollbackTransaction();

      this.logger.error(
        `❌ 角色 ${characterId} 存入金币失败: ${error.message}`
      );
      throw error;
    } finally {
      // 释放资源
      await queryRunner.release();
    }
  }

  /**
   * 金币从银行取出
   * @param characterId 角色ID
   * @param amount 取出金额
   * @param password 密码
   * @returns 操作结果
   */
  async withdrawGold(
    characterId: number,
    amount: number,
    password: string
  ): Promise<any> {
    if (amount <= 0) {
      throw new BadRequestException("取出金额必须大于0");
    }

    // 暂时不校验密码
    // if (!password || password !== "123456") {
    //   throw new BadRequestException("密码错误");
    // }

    const queryRunner = this.dataSource.createQueryRunner();

    try {
      // 开始事务
      await queryRunner.connect();
      await queryRunner.startTransaction();

      // 获取角色资源信息
      const resources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );

      if (!resources) {
        throw new BadRequestException("角色资源信息不存在");
      }

      // 检查钱庄金币余额是否足够
      if ((resources.balanceGold || 0) < amount) {
        throw new BadRequestException("钱庄金币余额不足");
      }

      // 确保amount是数字类型
      const numAmount = Number(amount);

      // 验证转换后的数字是否有效
      if (isNaN(numAmount)) {
        throw new BadRequestException("无效的金额格式");
      }

      // 从钱庄扣除金币，增加到普通金币
      await queryRunner.manager.update(
        CharacterResourcesEntity,
        { characterId },
        {
          balanceGold: () => `balanceGold - ${numAmount}`,
          gold: () => `gold + ${numAmount}`,
          updated_at: new Date(),
        }
      );

      // 提交事务
      await queryRunner.commitTransaction();

      this.logger.log(`✅ 角色 ${characterId} 成功取出金币 ${numAmount}`);

      return {
        success: true,
        message: "金币取出成功",
        data: {
          balanceGold: (+resources.balanceGold || 0) - numAmount,
          balanceMoney: resources.balanceMoney || 0,
          gold: +resources.gold + numAmount,
          money: resources.silver || 0,
        },
      };
    } catch (error: any) {
      // 回滚事务
      await queryRunner.rollbackTransaction();

      this.logger.error(
        `❌ 角色 ${characterId} 取出金币失败: ${error.message}`
      );
      throw error;
    } finally {
      // 释放资源
      await queryRunner.release();
    }
  }

  /**
   * 银币存入银行
   * @param characterId 角色ID
   * @param amount 存入金额
   * @returns 操作结果
   */
  async depositSilver(characterId: number, amount: number): Promise<any> {
    if (amount <= 0) {
      throw new BadRequestException("存入金额必须大于0");
    }

    const queryRunner = this.dataSource.createQueryRunner();

    try {
      // 开始事务
      await queryRunner.connect();
      await queryRunner.startTransaction();

      // 获取角色资源信息
      const resources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );

      if (!resources) {
        throw new BadRequestException("角色资源信息不存在");
      }

      // 检查普通银币余额是否足够
      if (resources.silver < amount) {
        throw new BadRequestException("普通银币余额不足");
      }

      // 确保amount是数字类型
      const numAmount = Number(amount);

      // 验证转换后的数字是否有效
      if (isNaN(numAmount)) {
        throw new BadRequestException("无效的金额格式");
      }

      // 扣除普通银币
      await queryRunner.manager.update(
        CharacterResourcesEntity,
        { characterId },
        {
          silver: () => `silver - ${numAmount}`,
          balanceMoney: () => `balanceMoney + ${numAmount}`,
          updated_at: new Date(),
        }
      );

      // 提交事务
      await queryRunner.commitTransaction();

      this.logger.log(`✅ 角色 ${characterId} 成功存入银币 ${numAmount}`);

      return {
        success: true,
        message: "银币存入成功",
        data: {
          balanceGold: resources.balanceGold || 0,
          balanceMoney: (+resources.balanceMoney || 0) + numAmount,
          gold: resources.gold || 0,
          money: +resources.silver - numAmount,
        },
      };
    } catch (error: any) {
      // 回滚事务
      await queryRunner.rollbackTransaction();

      this.logger.error(
        `❌ 角色 ${characterId} 存入银币失败: ${error.message}`
      );
      throw error;
    } finally {
      // 释放资源
      await queryRunner.release();
    }
  }

  /**
   * 银币从银行取出
   * @param characterId 角色ID
   * @param amount 取出金额
   * @param password 密码
   * @returns 操作结果
   */
  async withdrawSilver(
    characterId: number,
    amount: number,
    password: string
  ): Promise<any> {
    if (amount <= 0) {
      throw new BadRequestException("取出金额必须大于0");
    }

    // if (!password || password !== "123456") {
    //   throw new BadRequestException("密码错误");
    // }

    const queryRunner = this.dataSource.createQueryRunner();

    try {
      // 开始事务
      await queryRunner.connect();
      await queryRunner.startTransaction();

      // 获取角色资源信息
      const resources = await queryRunner.manager.findOne(
        CharacterResourcesEntity,
        {
          where: { characterId },
        }
      );

      if (!resources) {
        throw new BadRequestException("角色资源信息不存在");
      }

      // 检查钱庄银币余额是否足够
      if ((resources.balanceMoney || 0) < amount) {
        throw new BadRequestException("钱庄银币余额不足");
      }

      // 确保amount是数字类型
      const numAmount = Number(amount);

      // 验证转换后的数字是否有效
      if (isNaN(numAmount)) {
        throw new BadRequestException("无效的金额格式");
      }

      // 从钱庄扣除银币，增加到普通银币
      await queryRunner.manager.update(
        CharacterResourcesEntity,
        { characterId },
        {
          balanceMoney: () => `balanceMoney - ${numAmount}`,
          silver: () => `silver + ${numAmount}`,
          updated_at: new Date(),
        }
      );

      // 提交事务
      await queryRunner.commitTransaction();

      this.logger.log(`✅ 角色 ${characterId} 成功取出银币 ${numAmount}`);

      return {
        success: true,
        message: "银币取出成功",
        data: {
          balanceGold: resources.balanceGold || 0,
          balanceMoney: (+resources.balanceMoney || 0) - numAmount,
          gold: resources.gold || 0,
          money: +resources.silver + numAmount,
        },
      };
    } catch (error: any) {
      // 回滚事务
      await queryRunner.rollbackTransaction();

      this.logger.error(
        `❌ 角色 ${characterId} 取出银币失败: ${error.message}`
      );
      throw error;
    } finally {
      // 释放资源
      await queryRunner.release();
    }
  }
}
